package com.fr.ticket;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import com.alibaba.fastjson.JSONObject;


/**
 * @author 付荣
 * @version 创建时间：2019年4月9日 下午4:12:02
 */
public class ESUtils {
	private static TransportClient client = null;
	static {
		try {
			client = TransportClient.builder()
			    .settings(Settings.builder()
			        .put("cluster.name", "master")
			        .build())
			    .build()
			    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	private static final AdminClient adminClient = client.admin();
	private static final IndicesAdminClient indicesAdminClient = adminClient.indices();
	public static TransportClient getClient(){
		return client;
	}
	public static void createIndex(String index){
		CreateIndexRequest  createIndexRequest = new CreateIndexRequest(index);
		Settings.Builder settingsBuilder = Settings.settingsBuilder();
		settingsBuilder
				.put("number_of_shards", 1) // 设置分片数量
				.put("number_of_replicas", 1);
		createIndexRequest.settings(settingsBuilder);
		indicesAdminClient.create(createIndexRequest).actionGet();
	}
	
	public static void writeIndex(String index, String type, List<JSONObject> collections){
		if(CollectionUtils.isNotEmpty(collections)){
			BulkRequestBuilder bulkRequest = client.prepareBulk();
			for(JSONObject c : collections){
				IndexRequestBuilder b = client.prepareIndex(index, type).setId(c.getString("id")).setSource(c);
				bulkRequest.add(b);
			}
			bulkRequest.get();
		}
	}
	
	
}
